package com.nishop.web.suport;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import com.nishop.api.util.Identity;

public class UploadSuport {

	/**
	 * 创建文件到服务器
	 *
	 * @param file
	 * @return
	 */
	public static String createFileToServer(MultipartFile file, HttpServletRequest request) {
		String path = "";
		if (!file.isEmpty()) {
			try {
				// 使用UUID给图片重命名，并去掉四个“-”
				String name = Identity.uuidWithoutHyphen();
				// 获取文件的扩展名
				String ext = FilenameUtils.getExtension(file.getOriginalFilename());
				// 设置图片上传路径
				String url = request.getSession().getServletContext()
						.getRealPath("/WEB-INF/upload");

				File tmp = new File(url);

				if (!tmp.exists()) {
					tmp.mkdirs();
				}

				// 以绝对路径保存重名命后的图片
				file.transferTo(new File(url + "/" + name + "." + ext));

				path = "upload/" + name + "." + ext;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return path;
	}

}
